package cn.swh.guguanjia.controller;

import cn.swh.guguanjia.entity.Result;
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionController {

    /**
     * 统一处理异常
     *
     * @return
     **/

    @ExceptionHandler(value = KaptchaException.class)
    @ResponseBody
    public Result kaptchaExceptionHandler(KaptchaException kaptchaException) {
        if (kaptchaException instanceof KaptchaIncorrectException) {
            return new Result(false, "验证码不正确", null);
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            return new Result(false, "验证码未找到", null);
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            return new Result(false, "验证码过期", null);
        } else {
            return new Result(false, "验证码渲染失败", null);
        }

    }

    @ExceptionHandler
    @ResponseBody
    public Result doHandler(Exception e) {
        System.out.println("发生异常" + e.getLocalizedMessage());
        return new Result(false, "发生异常" + e.getLocalizedMessage(), null);
    }
}
